import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from typing import List
import logging

from notify.base import NotificationSender

logger = logging.getLogger(__name__)


class EmailSender(NotificationSender):
    """
    邮件发送实现类
    """

    def __init__(self, host: str, port: int, username: str, password: str, use_tls: bool = True):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.use_tls = use_tls
        self.server = None

    def connect(self) -> bool:
        """
        连接到SMTP服务器

        :return: 连接是否成功
        """
        try:
            self.server = smtplib.SMTP(self.host, self.port)
            if self.use_tls:
                self.server.starttls()
            self.server.login(self.username, self.password)
            logger.info("Successfully connected to SMTP server")
            return True
        except Exception as e:
            logger.error(f"Failed to connect to SMTP server: {e}")
            return False

    def disconnect(self) -> None:
        """
        断开SMTP服务器连接
        """
        if self.server:
            try:
                self.server.quit()
                logger.info("Disconnected from SMTP server")
            except Exception as e:
                logger.error(f"Error disconnecting from SMTP server: {e}")
            finally:
                self.server = None

    def send(self, subject: str, content: str, recipients: List[str], **kwargs) -> bool:
        """
        发送邮件

        :param subject: 邮件主题
        :param content: 邮件内容
        :param recipients: 收件人列表
        :param kwargs: 其他参数
        :return: 发送是否成功
        """
        if not self.server:
            if not self.connect():
                return False

        try:
            msg = MIMEMultipart()
            msg['From'] = self.username
            msg['To'] = ', '.join(recipients)
            msg['Subject'] = Header(subject, 'utf-8')

            # 添加邮件正文
            msg.attach(MIMEText(content, 'plain', 'utf-8'))

            # 发送邮件
            self.server.sendmail(self.username, recipients, msg.as_string())
            logger.info(f"Email sent successfully to {recipients}")
            return True
        except Exception as e:
            logger.error(f"Failed to send email: {e}")
            return False